<?php

namespace App\Admin\Forms\User;

use App\Models\Account;
use App\Models\User;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class RechargeForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $money = $input['money'] * 100;
        $user_id = $this->payload['id'];
        DB::transaction(function () use ($user_id, $money) {
            $user = User::query()->where('id', '=', $user_id)->lockForUpdate()->first();
            User::query()->where('id', $user_id)->increment('balance', $money);
            $user->save();
            (new Account())->store($user_id, $money, Account::SYSTEM_RECHARGE);
        });

        return $this
            ->response()
            ->success(trans('admin.succeeded'))
            ->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->text('money', '充值金额')->rules('required|numeric|min:1');
    }

}
